<template>
  <div class="container">
    <video class="video" ref="videoRef" muted autoplay />
  </div>
  <el-button type="primary" @click="cutImg">截图</el-button>
  <img class="flex" v-if="src" :src="src" alt="截图" />
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
//调用摄像
let videoRef = ref()
let videoStream = ref(null)
onMounted(() => {
  openCamera()
})
const openCamera = async () => {
  try {
    videoRef.value.srcObject = videoStream = await navigator.mediaDevices.getUserMedia({ video: true })
  } catch (e) {
    let message = ''
    if (['NotAllowedError', 'PermissionDeniedError'].includes(e.name)) {
      message = '浏览器没有授予摄像头权限'
    } else if (['NotFoundError', 'DevicesNotFoundError'].includes(e.name)) {
      message = '没有找到摄像头'
    } else if (['Device in use'].includes(e.name)) {
      message = '摄像头被占用'
    }
    // ElMessage.warning(message)
  }
}

// 拍照
let src = ref('')
const cutImg = () => {
  const canvas = document.createElement('canvas')
  canvas.width = 275
  canvas.height = 300
  // 源对象，范围x坐标，范围y坐标，范围宽度，范围高度，范围位于水平距离，范围位于垂直距离，裁剪宽度，代煎高度
  canvas.getContext('2d').drawImage(videoRef.value, 123, 0, 500, 500, 0, 0, 275, 360)
  const base64 = canvas.toDataURL('image/jpeg', 1)
  src.value = base64
  console.log(src.value, 'src.value ');

}

// 关闭摄像头
const closeCamera = () => {
  videoRef.value.srcObject = null // 重置摄像头
  videoStream.value?.getTracks().forEach((track) => {
    track.stop() // 关闭摄像头轨道
  })
}
</script>

<style scoped lang="scss">
.container {
  width: 50%;
  height: 500px;
  margin: 0 auto;
  background-color: #333;
  margin-top: 40px;

  .video {
    width: 100%;

    height: 100%;
  }
}
</style>
